﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using Telerik.Web.UI;
using KPIS.GERP.GAMS.DAL;
using KPIS.GERP.GAMS.MODEL;
using System.Transactions;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using KPIS.DBM;

namespace KPIS.GERP.GAMS.APP.App_UI.Forms
{
    public partial class ACM_Inbox : System.Web.UI.Page
    {
        CultureInfo _thCulture = new CultureInfo("th-TH");
        Commons.Main main = new Commons.Main();
        D_BGM_MAS_Source source = new D_BGM_MAS_Source();
        D_ACM_Calculate_Depreciation dep = new D_ACM_Calculate_Depreciation();
        D_ACM_GENERAL_Ledger gl = new D_ACM_GENERAL_Ledger();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                for (int i = 1; i <= 12; i++)
                {
                    DateTime Tempdate = new DateTime(DateTime.Now.Year, i, 1);
                    RadComboBoxItem item = new RadComboBoxItem();
                    item.Text = Tempdate.ToString("MMMM", _thCulture);
                    item.Value = Convert.ToInt32(i).ToString();

                    ddlBgmMonth.Items.Add(item);
                    item.DataBind();
                }

                ddlBgmMonth.SelectedValue = "9";
                txtBgmYear.Text = source.GetCurrentBgmYear();
            }
        }

        protected void grdACMVersion_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {

            if (!e.IsFromDetailTable)
            {
                grdACMAccountAuto.DataSource = dep.GetAssets();

            }
        }

        protected void LoadGridMaster(string SelectBgmYear, string selectMonth)
        {
            grdACMAccountAuto.DataSource = dep.GetAssets();
            grdACMAccountAuto.DataBind();
        }

        protected void cmdFilter_Click(object sender, EventArgs e)
        {
            int? BgmYear = main.ConvertNullInt(txtBgmYear.Text);
            int? Month = main.ConvertNullInt(ddlBgmMonth.SelectedValue);

            if (!BgmYear.HasValue || !Month.HasValue)
            {
                main.MessageAlert(Page, "กรุณากรอกข้อมูลให้ถูกต้อง");
                return;
            }

            DateTime CalDate = new DateTime((Month >= 10 ? BgmYear - 544 : BgmYear - 543).Value, Month.Value, 1).AddMonths(1).AddDays(-1);

            CalculateDepre(BgmYear.Value, CalDate);
        }

        protected void CalculateDepre(int BgmYear, DateTime CalDate)
        {
            //get latest caldepre
            DBManager dbManager = new DBManager(SystemInfo._DataProvider, ConfigurationSettings.AppSettings["ConnectionString"].ToString());
            DataTable dtbAsset = dep.GetAssets(CalDate);
            IList<Depre> depreList = new List<Depre>();

            try
            {
                string strSQL = "";
                string TranGrpSeq = gl.GetNextTranGrpSeq().ToString();
                string TranCode1 = gl.GetNextTranCode("1", BgmYear.ToString(), "A");
                string TranCode2 = gl.GetNextTranCode("11", BgmYear.ToString(), "A");
                string FiscalPeriod = main.GetFiscalPeriod(CalDate);
                string TranSeq1 = "";
                string TranSeq2 = "";
                dbManager.Open();
                dbManager.BeginTransaction();

                foreach (DataRow drAsset in dtbAsset.Rows)
                {
                    dbManager.CreateParameters(1);
                    dbManager.AddParameters(0, "@AssetId", drAsset["AssetId"].ToString());

                    strSQL = @"
select a.AssetId, a.AssetCode
, a.AssetDate, a.Price, a.LifeYear, a.BgSourceId
, grp.AssetAccountId
, grp.DepreAccountId
, grp.CumdepreAccountId
, max(COALESCE(dep.CalculatedDate, a.AssetDate)) as CalculatedDate
, sum(COALESCE(dep.DepAmount, 0)) as DepAmount
from IcmAsset a
left join IcmAssetDepreciation dep on a.AssetId = dep.AssetId
inner join IcmMasResourceItem item on a.ResItemId = item.ResItemId
inner join IcmMasResourceSubGroup sub on item.ResSubGrpId = sub.ResSubGrpId
inner join IcmMasResourceGroup grp on sub.ResGrpId = grp.ResGrpId

where a.AssetId = @AssetId
and a.RecordStatus <> 'D'

group by a.AssetId, a.AssetCode, a.AssetDate, a.Price, a.LifeYear, a.BgSourceId
, grp.AssetAccountId
, grp.DepreAccountId
, grp.CumdepreAccountId";
                    DataTable dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                    if (dtb.Rows.Count > 0)
                    {
                        DataRow dr = dtb.Rows[0];
                        double Price = main.ConvertNullDouble(dr["Price"]) ?? 0;
                        double AccumDepreAmount = main.ConvertNullDouble(dr["DepAmount"]) ?? 0;
                        double LifeYear = main.ConvertNullDouble(dr["LifeYear"]) ?? 0;
                        DateTime LastCalDate = main.ConvertNullDateTime(dr["CalculatedDate"]) ?? DateTime.Today;

                        int Days = Convert.ToInt32((CalDate - LastCalDate).TotalDays);
                        double DepreAmount = (Price / (LifeYear * 365)) * Days;

                        if (Price <= DepreAmount + AccumDepreAmount)
                        {
                            DepreAmount = Price - AccumDepreAmount - 1;
                        }

                        if (DepreAmount < 0)
                        {
                            DepreAmount = 0;
                            continue;
                        }

                        if (string.IsNullOrEmpty(dr["DepreAccountId"].ToString()) || string.IsNullOrEmpty(dr["CumdepreAccountId"].ToString()))
                        {
                            throw new Exception("ครุภัณฑ์รหัส " + dr["AssetCode"].ToString() + " ไม่มีการผูกบัญชีไว้");
                        }

                        Depre depreInfo = new Depre()
                        {
                            BgmSourceSeq = dr["BgSourceId"].ToString(),
                            AccumDepreAccId = dr["CumdepreAccountId"].ToString(),
                            DepreAccId = dr["DepreAccountId"].ToString(),
                            Amount = Math.Round(DepreAmount, 2),
                        };

                        depreList.Add(depreInfo);

                        dbManager.CreateParameters(7);
                        dbManager.AddParameters(0, "@AssetId", dr["AssetId"].ToString());
                        dbManager.AddParameters(1, "@CalculatedDate", CalDate);
                        dbManager.AddParameters(2, "@DepAmount", DepreAmount);
                        dbManager.AddParameters(3, "@TranGrpId", TranGrpSeq);
                        dbManager.AddParameters(4, "@RecordStatus", "W");
                        dbManager.AddParameters(5, "@CreatedBy", Session["EmpSeq"].ToString());
                        dbManager.AddParameters(6, "@CreatedWhen", DateTime.Now);

                        strSQL = @"
INSERT INTO IcmAssetDepreciation
(AssetId, CalculatedDate, DepAmount, TranGrpId, RecordStatus, CreatedBy, CreatedWhen)
values
(@AssetId, @CalculatedDate, @DepAmount, @TranGrpId, @RecordStatus, @CreatedBy, @CreatedWhen)
";

                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                    }
                }

                IList<Depre> depreList2 = depreList.GroupBy(g => new { g.AccumDepreAccId, g.DepreAccId, g.BgmSourceSeq })
                    .Select(m => new Depre()
                    {
                        BgmSourceSeq = m.Key.BgmSourceSeq,
                        AccumDepreAccId = m.Key.AccumDepreAccId,
                        DepreAccId = m.Key.DepreAccId,
                        Amount = m.Sum(g => g.Amount),
                    }).OrderBy(m => m.BgmSourceSeq).ToList();

                strSQL = @"
INSERT INTO acm_transection
(tran_type, fiscal_period, tran_grp_seq, tran_code, tran_date, bgm_year, bgm_source_seq, ref_no, tran_name, record_status, created_by, created_when)
values
(@tran_type, @fiscal_period, @tran_grp_seq, @tran_code, @tran_date, @bgm_year, @bgm_source_seq, @ref_no, @tran_name, @record_status, @created_by, @created_when);
select scope_identity();
";

                if (depreList2.Where(m => m.BgmSourceSeq == "1").ToList().Count > 0)
                {
                    dbManager.CreateParameters(12);
                    dbManager.AddParameters(0, "@tran_type", "A");
                    dbManager.AddParameters(1, "@fiscal_period", FiscalPeriod);
                    dbManager.AddParameters(2, "@tran_grp_seq", TranGrpSeq);
                    dbManager.AddParameters(3, "@tran_code", TranCode1);
                    dbManager.AddParameters(4, "@tran_date", CalDate);
                    dbManager.AddParameters(5, "@bgm_year", BgmYear);
                    dbManager.AddParameters(6, "@bgm_source_seq", 1);
                    dbManager.AddParameters(7, "@ref_no", TranCode1);
                    dbManager.AddParameters(8, "@tran_name", "ปรับปรุงค่าเสื่อมราคาครุภัณฑ์ ณ " + CalDate.ToString("MMMM", CultureInfo.CurrentCulture) + " ปีงบประมาณ " + BgmYear);
                    dbManager.AddParameters(9, "@record_status", "W");
                    dbManager.AddParameters(10, "@created_by", Session["EmpSeq"].ToString());
                    dbManager.AddParameters(11, "@created_when", DateTime.Now);

                    TranSeq1 = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0].ToString();
                }

                if (depreList2.Where(m => m.BgmSourceSeq == "11").ToList().Count > 0)
                {
                    dbManager.CreateParameters(12);
                    dbManager.AddParameters(0, "@tran_type", "A");
                    dbManager.AddParameters(1, "@fiscal_period", FiscalPeriod);
                    dbManager.AddParameters(2, "@tran_grp_seq", TranGrpSeq);
                    dbManager.AddParameters(3, "@tran_code", TranCode2);
                    dbManager.AddParameters(4, "@tran_date", CalDate);
                    dbManager.AddParameters(5, "@bgm_year", BgmYear);
                    dbManager.AddParameters(6, "@bgm_source_seq", 11);
                    dbManager.AddParameters(7, "@ref_no", TranCode2);
                    dbManager.AddParameters(8, "@tran_name", "ปรับปรุงค่าเสื่อมราคาครุภัณฑ์ ณ " + CalDate.ToString("MMMM", CultureInfo.CurrentCulture) + " ปีงบประมาณ " + BgmYear);
                    dbManager.AddParameters(9, "@record_status", "W");
                    dbManager.AddParameters(10, "@created_by", Session["EmpSeq"].ToString());
                    dbManager.AddParameters(11, "@created_when", DateTime.Now);

                    TranSeq2 = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0].ToString();
                }

                foreach (Depre depreInfo2 in depreList2)
                {
                    if (depreInfo2.Amount > 0)
                    {
                        dbManager.CreateParameters(7);
                        dbManager.AddParameters(0, "@tran_seq", depreInfo2.BgmSourceSeq == "1" ? TranSeq1 : TranSeq2);
                        dbManager.AddParameters(1, "@amount", depreInfo2.Amount);
                        dbManager.AddParameters(2, "@record_status", "W");
                        dbManager.AddParameters(3, "@created_by", Session["EmpSeq"].ToString());
                        dbManager.AddParameters(4, "@created_when", DateTime.Now);

                        dbManager.AddParameters(5, "@account_seq1", depreInfo2.DepreAccId);
                        dbManager.AddParameters(6, "@account_seq2", depreInfo2.AccumDepreAccId);
                        strSQL = @"
INSERT INTO acm_transection_dtls
(tran_seq, account_seq, dr_or_cr, amount, record_status, created_by, created_when)
values
(@tran_seq, @account_seq, @dr_or_cr, @amount, @record_status, @created_by, @created_when)
";
                        strSQL = strSQL.Replace("@dr_or_cr", "'Dr'");
                        strSQL = strSQL.Replace("@account_seq", "@account_seq1");
                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                        strSQL = strSQL.Replace("@dr_or_cr", "'Cr'");
                        strSQL = strSQL.Replace("'Dr'", "'Cr'");
                        strSQL = strSQL.Replace("@account_seq1", "@account_seq2");
                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                    }
                }

                dbManager.CommitTransaction();
            }
            catch (Exception ex)
            {
                dbManager.RollBackTransaction();
                main.MessageAlert(Page, "พบข้อผิดพลาดขณะประมวลผล กรุณาตรวจสอบข้อมูลอีกครั้ง " + ex.Message);
            }
            finally
            {
                dbManager.Dispose();
            }
        }

        //protected void btnSave_Click(object sender, EventArgs e)
        //{
        //    string SelectBgmYear = txtBgmYear.Text;
        //    string selectMonth = ddlBgmMonth.SelectedValue;
        //    int nEmpSeq = Convert.ToInt32(Session["EmpSeq"]);
        //    int AssetId = Convert.ToInt32(Session["asset_id"]);

        //    D_ACM_DepreciationType DP = new D_ACM_DepreciationType();
        //    string SumCk = DP.GetCheckday(Convert.ToInt32(SelectBgmYear));
        //    if (Convert.ToInt32(SumCk) == 1)
        //    {
        //       // Click(1); 
        //    }
        //    else
        //    {
        //        DP.InsertDPAccount(SelectBgmYear, selectMonth, nEmpSeq);
        //    }
        //}

        //protected void Click(int Process)
        //{
        //    if (Process == 1)
        //    {
        //        string message = "คูณไม่สามารถบันทึกบัญชีในรอบปีนี้ได้เนื่องจากคุณได้ทำการบันทึกบัญชีในปี" + DateTime.Now.Year + "แล้ว";
        //        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //        sb.Append("<script type = 'text/javascript'>");
        //        sb.Append("window.onload=function(){");
        //        sb.Append("alert('");
        //        sb.Append(message);
        //        sb.Append("')};");
        //        sb.Append("</script>");
        //        ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
        //    }
        //}
    }

}
